How to make a php login form without page refresh using php and javascript 您所在的位置:网站首页 how to submit a form without page refresh in How to make a php login form without page refresh using php and javascript

How to make a php login form without page refresh using php and javascript

2023-04-14 10:06| 来源: 网络整理| 查看: 265

How to submit a login form without page refresh using php and javascript

Updated: 13-Apr-2023 | Tags: Javascript Tutorials | Views: 7

Introduction

Hi guys, In this article we are gonna see how to submit a form without a page refresh using javascript, Ajax, and php. If you think that this is something difficult to do, i have to say that it isn't.

I will try to explain everything in details. But if you still have questions, feel free to leave a comment.

Quick answer

Create a form with a username and a password field. In the javascript file target the form element and add an "onsubmit eventlistener" to it. Grab the username and password, and create an object to store them. Use the fetch method to send a post request, that contains the above object, to the php file. In the php file use the file_get_contents("php://input") to access the Ajax request. You have also to decode the incoming JSON data in an array, or an object. Now you can work with the data. Live demo

I have created a live example, so you can try it out and see what we are going to code. We are going to validate the input fields for empty values in the php file. If a field is empty we are going to display an error under it.

Now that you have tried out the live demo, let's see what files we need to build it.

Project's folder

We need an index.html file to write the login form. We need a script.js javascript file to write the javascript code. We need a script.php file to validate the password and the username. And we have a styles.css stylesheet file to make the form look pretty.

Now that we have set-up the file structure, let's code.

The index.html file

First we will create a basic html page structure. The important things here are the link to the styles.css file in line 6. And the script tag that points to the javascript file in line 12.

!DOCTYPE html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> link rel="stylesheet" href="styles.css"> title>PHP ajax tutorial/title> /head> body> script src="script.js">/script> /body> /html> Creating the login form

Next inside the body tags we will create the login form

form> label>Username span>Choose a username/span>/label> input type="text" name="username" value="" > p class="error username-error">/p> label>Password span>Choose a password/span> /label> input type="password" name="password" value=""> p class="error password-error">/p> input type="submit" name="sign-in" value="Sign In"> p class="success">/p> /form>

Explaining the login form

First of all in line 10 we have the form element. Notice that we don't have an action, neither a method attribute. We don't need them because we will send the data to the php file, with javascript. In line 12 we have the username input field, and under it in line 13 we have a paragraph element which has two classes. A class of error and a unique class of username-error. The error class is hidden by default in the css file, so the paragraph element is not visible. We are going to change the visibility of the element using javascript, if there is an error that we have to show. In line 16 we have the password input field, and in line 17 we have another error placeholder, where the unique class here is "password-error". This element is also hidden because it has the error class applied. In line 19 we have the form's submit button. And in line 20 we have another placeholder that will show the success message. This element is also hidden by default, in the css file. We are going to populate the error, and the success placeholders from the javascript file. There is nothing more to say about the form element, it is very simple. So let's go and write the javascript code. The Javascript code

Here is the javascript code in the script.js file. Scroll down where i am explaining all the code line by line.

let form = document.forms[0]; form.addEventListener("submit", (event) => { event.preventDefault(); document.querySelector(".username-error").style.display = "none"; document.querySelector(".password-error").style.display = "none"; document.querySelector(".success").style.display = "none"; let loginData = { username: form.username.value, password: form.password.value } let params = { method: "POST", headers: { "Content-Type": "application/json; charset=utf-8" }, body: JSON.stringify(loginData) } fetch("script.php", params) .then(function(response){ if(response.status == 200){ return response.text(); } }) .then(function(data){ if(data == "error-01"){ document.querySelector(".username-error").style.display = "block"; document.querySelector(".username-error").innerHTML = "Username field is empty"; } if(data == "error-02"){ document.querySelector(".password-error").style.display = "block"; document.querySelector(".password-error").innerHTML = "Password field is empty"; } if(data == "success"){ document.querySelector(".success").style.display = "block"; document.querySelector(".success").innerHTML = "Thank you for your registration"; } }); }); Let's explain the above javascript code

The first thing that we do in the javascript file is to target the form element and store it in a variable.

let form = document.forms[0]; document.forms ... gives us an array of all html forms that we have in the index file. But since we have only one form, this form is stored in index zero [0].

Next we are taking the form variable and we assign an eventlistener to it.

form.addEventListener("submit", (event) => { We set the first argument to "submit", and in the second argument we have a function, and we pass-in the event object. I need the event object to prevent the form to submit the data to the server. You will see in the next line.

In line 3 we call the preventDefault() method that the event object has to stop the form to send the data to the server. This is how we stop the browser to refresh the page, or to go to a different php page.

event.preventDefault();

In the html form section i said the the errors and success placeholders are hidden by default in the css file. So in this code block we hide the placeholders again, in case that we have displayed an error or the success message in a prior submit action.

document.querySelector(".username-error").style.display = "none"; document.querySelector(".password-error").style.display = "none"; document.querySelector(".success").style.display = "none";

Since the browser will not refresh the page we have to do this manually every time someone clicks on the submit button.

In line 9 we create an object named loginData and we store the username and the password that the user has entered. We are gonna send this object to the script.php file.

let loginData = { username: form.username.value, password: form.password.value }

In line 14 we create an object named params (as parameters), that will hold the HTTP request's parameters which we are going to send with the fetch method.

let params = { method: "POST", headers: { "Content-Type": "application/json; charset=utf-8" }, body: JSON.stringify(loginData) } In line 15, we set the method to "POST", like we would do in an html form. I line 17 we set the "Content-type" header to application/json, so the php file will know the type of data that we are sending. And in line 19 in the body property we pass-in the loginData object. But as you see we have to convert it to a JSON string using the JSON.stringify method.

In line 22 we use the fetch method to send the data to the php file as an AJAX request.

fetch("script.php", params) In the first parameter we set the path to the php file that will handle the request, which is the script.php file. And in the second parameter we pass-in the params object which holds the request's instructions.

In line 23 we have the then method chained to the fetch method to get the response from the php file.

.then(function(response){ if(response.status == 200){ return response.text(); } }) The then method takes as an argument a function. Which function takes as an argument a variable that will hold the response object. You can name the variable anything you like. I named the variable response so it makes more sense. In line 24 we check the status of our response. If the value is 200 means that the response were successful. In line 25 we return the text of the response object using the text() method. We use the text() method, because we will return text as a response from the php file, when we validating the username and password. You will see in the next code block and in the php file when we get there.

Next we chain another then() method to grab the data that the text() method returns.

.then(function(data){ if(data == "error-01"){ document.querySelector(".username-error").style.display = "block"; document.querySelector(".username-error").innerHTML = "Username field is empty"; } if(data == "error-02"){ document.querySelector(".password-error").style.display = "block"; document.querySelector(".password-error").innerHTML = "Password field is empty"; } if(data == "success"){ document.querySelector(".success").style.display = "block"; document.querySelector(".success").innerHTML = "Thank you for your registration"; } }); }); // End of the event-listener function Again we pass-in a callback function in the then() method. The callback function's argument which is data, holds now the raw text the we will send from the php file. From the php file, if there is an empty username we will return the string "error-01". If there is an empty password value the php file will return the string "error-02". And if everything goes well the php file will return the string "success". You will see when we get to the php file. So based on the response of the php file we have three if statements. In line 29, if the data variable is equal to "error-01", that means we have an empty username. So in line 30 we un-hide the username-error placeholder, and we display a message that the "Username field is empty" in line 31. We have the same concept in line 33 with the password field, and in line 37 with the success placeholder.

That is all the javascript code that we need, now let's go to the script.php file to write the input validation.

The PHP code

This is the code that we have in the script.php file. Basically we fetch the Ajax request from the javascript file, and validate the username and password.

?php if(isset($_POST)){ $login_data = file_get_contents("php://input"); $login_data = json_decode($login_data, true); $username = trim($login_data['username']); $password = trim($login_data['password']); if(empty($username)){ echo "error-01"; }else{ if(empty($password)){ echo "error-02"; }else{ echo "success"; } } } Explaining the php code In line 2 we check if there is a POST request. In line 3 we fetch the incoming request from the javascript file using the file_get_contents() function, and we store the data in the $login_data variable. The php://input is a PHP stream that allows us to read raw data from the request body. In line 4 we decode the JSON data to an php array using the json_decode() function, and we store the decoded data back to the $login_data variable. The keyword true tells the function to return an array. If we omit it, the function will return an object. Next in line 5 and 6 we trim the incoming username and password, and we store them in the $username and $password variables. The next if statement simply says: If the username is empty echo the string "error-01". Else if the password is empty echo the string "error-02". And if both fields have values, echo the string "success". Remember that we checked those strings in the javascript file to display the corresponding message.

And that is all the php code that we need. Next we are going too see a couple of rules in the css file.

The CSS code

Now the important stuff in the css file is the .error and .success class. Both elements are hidden by setting the display property to display: none.

.error{ color: #af4242; background-color: #fde8ec; padding: 10px; display: none; transform: translateY(-20px); font-size: 14px; } .success{ margin-bottom: 30px; color: green; background-color: #d2ffd2; padding: 10px; display: none; }

Download the free source code to get the whole css file.

Summary

And that's it guys, we saw how the send a form to the server without a page refresh using javascript and an Ajax request. Also we did a simple validation in the php file just to see how to catch the server's response and show messages in the html form.

Source code

Thanks for reading, i hope you find the article helpful. Please leave a comment if you find any errors, so i can update the page with the correct code.

You can download the source code and use it in any way you like.

Times downloaded: 2

View on Youtube

Not recorded yet. 😥

If you feel like saying thanks, you can buy me a coffee

Related Articles How to toggle a slide effect with JavaScript How browser's local storage works Preview and validate an image with JavaScript Creating the front end of a rating system with css and javascript How to send a javascript object to php Docking Station USB C to Dual HDMI Adapter, USB C Hub Dual HDMI Monitors for Windows,USB C Adapter with Dual HDMI,3 USB Port,PD Compatible for Dell XPS 13/15, Lenovo Yoga,etc USB C Adapter USB C Dual HDMI Adapter USB C Docking Station for Windows Laptops. Buy on Amazon Affiliate products Comment section


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有